<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>多功能Ref | 刘超的博客</title><meta name="author" content="刘超"><meta name="copyright" content="刘超"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Ref 基本概念和使用Ref 对象的创建  类组件创建 Ref 对象 this.currentDom &#x3D; React.createRef(null);  React.createRef 的底层逻辑实现很简单 export function createRef()&#123;  const refObject &#x3D; &#123;    current:null  &#125;  return refO">
<meta property="og:type" content="article">
<meta property="og:title" content="多功能Ref">
<meta property="og:url" content="https://leachliu.gitee.io/2022/01/05/react/%E5%A4%9A%E5%8A%9F%E8%83%BDRef/index.html">
<meta property="og:site_name" content="刘超的博客">
<meta property="og:description" content="Ref 基本概念和使用Ref 对象的创建  类组件创建 Ref 对象 this.currentDom &#x3D; React.createRef(null);  React.createRef 的底层逻辑实现很简单 export function createRef()&#123;  const refObject &#x3D; &#123;    current:null  &#125;  return refO">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://leachliu.gitee.io/images/avatar.webp">
<meta property="article:published_time" content="2022-01-04T16:00:00.000Z">
<meta property="article:modified_time" content="2023-11-03T07:37:06.448Z">
<meta property="article:author" content="刘超">
<meta property="article:tag" content="Ref">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://leachliu.gitee.io/images/avatar.webp"><link rel="shortcut icon" href="/images/favicon.ico"><link rel="canonical" href="https://leachliu.gitee.io/2022/01/05/react/%E5%A4%9A%E5%8A%9F%E8%83%BDRef/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: {"appId":"VFZO06XK8A","apiKey":"1202cec78a85d208874b3c9cbcd0e212","indexName":"index total","hits":{"per_page":10},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '多功能Ref',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-11-03 15:37:06'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/ethan4116-blog/lib/css/plane_v2.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css"  media="defer" onload="this.media='all'"><script defer src="/js/custom.js"></script><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><!-- hexo injector head_end start --><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/tag_plugins.css" media="defer" onload="this.media='all'"><script src="https://npm.elemecdn.com/hexo-butterfly-tag-plugins-plus@latest/lib/assets/carousel-touch.js"></script><!-- hexo injector head_end end --><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/images/avatar.webp" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="刘超的博客"><span class="site-name">刘超的博客</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">多功能Ref</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-01-04T16:00:00.000Z" title="发表于 2022-01-05 00:00:00">2022-01-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-11-03T07:37:06.448Z" title="更新于 2023-11-03 15:37:06">2023-11-03</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/react/">react</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="多功能Ref"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h2 id="Ref-基本概念和使用"><a href="#Ref-基本概念和使用" class="headerlink" title="Ref 基本概念和使用"></a>Ref 基本概念和使用</h2><p><font color="black" size="4">Ref 对象的创建</font></p>
<ul>
<li><p>类组件创建 Ref 对象</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="variable language_">this</span>.<span class="property">currentDom</span> = <span class="title class_">React</span>.<span class="title function_">createRef</span>(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>React.createRef 的底层逻辑实现很简单</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">function</span> <span class="title function_">createRef</span>(<span class="params"></span>)&#123;</span><br><span class="line">  <span class="keyword">const</span> refObject = &#123;</span><br><span class="line">    <span class="attr">current</span>:<span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> refObject;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;&emsp;createRef 只做了一件事,就是创建了一个对象,对象上的 current 属性,用于保存通过 ref 获取的 DOM 元素,组件实例等。createRef 一般用于类组件创建 ref 对象,可以将 ref 绑定在类组件实例上,这样更方便后续操作 ref<br>&emsp;<font color="red">注意,不要在函数中使用 createRef,否则会造成 ref 对象内容丢失等情况</font></p>
</li>
<li><p>函数组件创建 Ref 对象</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; useRef &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span></span><br><span class="line"><span class="keyword">const</span> ref = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>

<p>&emsp;类组件有一个实例 instance 能够维护 ref 这种信息。但是函数组件每次更新都会重新更新函数,所有变量都会重新声明,所以不能像 createRef 那样暴露出去<br>&emsp;hooks 为了解决这个问题,使 hooks 和函数组件的 fiber 相关联,将 useRef 产生的对象挂载到函数组件对应的 fiber 上,只要组件不被销毁,函数对应的 fiber 对象一直在,ref 等信息就会一直被保存下来</p>
</li>
</ul>
<h2 id="类组件获取-Ref-的方式"><a href="#类组件获取-Ref-的方式" class="headerlink" title="类组件获取 Ref 的方式"></a>类组件获取 Ref 的方式</h2><ul>
<li><p>ref 属性是一个字符串</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">&lt;div ref=<span class="string">&quot;currentDom&quot;</span>&gt;&lt;/div&gt;</span><br></pre></td></tr></table></figure>

<p>&emsp;用一个字符串 ref 标记 DOM 元素,一个类组件(函数组件没有实例,不能被 Ref 标记),React 会在底层逻辑判断,会判断类型是 DOM 元素还是类组件,DOM 元素会把真实 DOM 绑定在组件 this.$refs属性上,如果是类组件会把ref属性绑定在子组件this.$refs 上</p>
</li>
<li><p>ref 属性是一个函数</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">currentDom = <span class="literal">null</span></span><br><span class="line">&lt;div ref=&#123;<span class="function">(<span class="params">node</span>)=&gt;</span> <span class="variable language_">this</span>.<span class="property">currentDom</span> = node &#125;&gt;&lt;/div&gt;</span><br></pre></td></tr></table></figure>

<p>&emsp;当用一个函数来标记 Ref 的时候,将作为 callback 形式,等到真实 DOM 创建阶段,执行 callback,获取的 DOM 元素或者组件实例,将以回调函数的第一个参数形式传入</p>
</li>
<li><p>ref 属性是一个对象</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">currentDom = <span class="title class_">React</span>.<span class="title function_">createRef</span>(<span class="literal">null</span>);</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">ref</span>=<span class="string">&#123;this.currentDom&#125;</span>&gt;</span>Ref对象模式获取元素或组件<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br></pre></td></tr></table></figure></li>
</ul>
<h2 id="Ref-高阶用法"><a href="#Ref-高阶用法" class="headerlink" title="Ref 高阶用法"></a>Ref 高阶用法</h2><p><font color="black" size="3">forwardRef 转发 Ref</font></p>
<p>&emsp;forwardRef 的初衷就是为了解决 Ref 不能跨层级捕获和传递的问题。forwardRef 接受了父元素标记的 Ref 信息,并把它转发下去,使得子组件可以接受到上一层级或者更上一层级的 ref</p>
<ul>
<li><p>跨层级获取<br>比如通过标记子组件,获取孙组件的某一 DOM 元素,或者是实例</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//孙组件</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">son</span>(<span class="params">props</span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> &#123; grandRef &#125; = props;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span>i am alien<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">span</span> <span class="attr">ref</span>=<span class="string">&#123;grandRef&#125;</span>&gt;</span>这个是想要获取的元素<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//父组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Father</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">construcotr</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(props);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">son</span> <span class="attr">ref</span>=<span class="string">&#123;this.props.grandRef&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//forwardRef转发</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">NewFather</span> = <span class="title class_">React</span>.<span class="title function_">forwardRef</span>(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> (</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">Father</span> <span class="attr">grandRef</span>=<span class="string">&#123;ref&#125;</span> &#123;<span class="attr">...props</span>&#125; /&gt;</span></span></span><br><span class="line">));</span><br><span class="line"><span class="comment">//爷组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">GrandFather</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">props</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(props);</span><br><span class="line">  &#125;</span><br><span class="line">  node = <span class="literal">null</span>;</span><br><span class="line">  <span class="title function_">componeneDidMount</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">node</span>); <span class="comment">// span text这个是想要获取的元素</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">NewFather</span> <span class="attr">ref</span>=<span class="string">&#123;(node)</span> =&gt;</span> (this.node = node)&#125; /&gt;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;上述所示,forwardRef 把 ref 变成了通过 props 传递和转发</p>
</li>
<li><p>合并转发 ref</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 表单组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Form</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>...<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// index 组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Index</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span> &#123;</span><br><span class="line">  <span class="title function_">componentDidMount</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; forwardRef &#125; = <span class="variable language_">this</span>.<span class="property">props</span>;</span><br><span class="line">    forwardRef.<span class="property">current</span> = &#123;</span><br><span class="line">      <span class="attr">form</span>: <span class="variable language_">this</span>.<span class="property">form</span>, <span class="comment">// 给form组件实例 ，绑定给 ref form属性</span></span><br><span class="line">      <span class="attr">index</span>: <span class="variable language_">this</span>, <span class="comment">// 给index组件实例 ，绑定给 ref index属性</span></span><br><span class="line">      <span class="attr">button</span>: <span class="variable language_">this</span>.<span class="property">button</span>, <span class="comment">// 给button dom 元素，绑定给 ref button属性</span></span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  form = <span class="literal">null</span>;</span><br><span class="line">  button = <span class="literal">null</span>;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> (</span><br><span class="line">      <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">ref</span>=<span class="string">&#123;(button)</span> =&gt;</span> (this.button = button)&#125;&gt;点击<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">Form</span> <span class="attr">ref</span>=<span class="string">&#123;(form)</span> =&gt;</span> (this.form = form)&#125; /&gt;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ForwardRefIndex</span> = <span class="title class_">React</span>.<span class="title function_">forwardRef</span>(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> (</span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">Index</span> &#123;<span class="attr">...props</span>&#125; <span class="attr">forwardRef</span>=<span class="string">&#123;ref&#125;</span> /&gt;</span></span></span><br><span class="line">));</span><br><span class="line"><span class="comment">// home 组件</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span> <span class="title function_">Home</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> ref = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br><span class="line">  <span class="title function_">useEffect</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ref.<span class="property">current</span>);</span><br><span class="line">  &#125;, []);</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">ForwardRefIndex</span> <span class="attr">ref</span>=<span class="string">&#123;ref&#125;</span> /&gt;</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>&emsp;<font color="red" size="3">forwardRef</font>,让 ref 通过 props 传递,那么 ref 对象就可以通过 props 的形式,提供给子孙组件消费,当然子孙组件也可以改变 ref 里面的属性</p>
</li>
</ul>
<h2 id="高阶组件转发"><a href="#高阶组件转发" class="headerlink" title="高阶组件转发"></a>高阶组件转发</h2><p>&emsp;如果通过高阶组件包裹一个原始类组件,就会产生一个问题,如果高阶组件 HOC 没有处理 ref,那么高阶组件本身会返回一个新组件,所以当使用 HOC 包装后组件的时候，标记的 ref 会指向 HOC 返回的组件,而并不是 HOC 包裹的原始类组件,使用 forwardRef 可以解决这个问题</p>
<ul>
<li><p>ref 组件实现通信</p>
<p>&emsp;<font color="black" size="2">类组件 ref</font><br>&emsp;对于类组件可以直接通过 ref 直接获取组件实例,实现组件通信</p>
</li>
<li><p>函数组件 forwardRef + useImperativeHandle</p>
<p>&emsp;对于函数组件本身是没有实例的,但是 React hooks 提供了,useImperativeHandle 一方面第一个参数接受父组件传递的 ref 对象,另一方面第二个参数是一个函数,函数返回值,作为 ref 获取的内容。 一起看下 useImperativeHandel 的使用</p>
<ul>
<li>第一个参数 ref: 接受 forwardRef 传递过来的 ref。</li>
<li>第二个参数 createHandle: 处理函数,返回值作为暴露给父组件的 ref 对象</li>
<li>第三个参数 deps: 依赖项 deps,依赖项更改成新的 ref 对象</li>
</ul>
</li>
</ul>
<p>&emsp;forwardRef + useImperativeHandle 可以完全让函数组件也能流畅使用 Ref 通信,其原理如下图<br><img src=""></p>
<pre><code><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 子组件</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Son</span> (props,ref) &#123;</span><br><span class="line">  <span class="keyword">const</span> inputRef = <span class="title function_">useRef</span>(<span class="literal">null</span>)</span><br><span class="line">  <span class="keyword">const</span> [ inputValue , setInputValue ] = <span class="title function_">useState</span>(<span class="string">&#x27;&#x27;</span>)</span><br><span class="line">  <span class="title function_">useImperativeHandle</span>(ref,<span class="function">()=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">const</span> handleRefs = &#123;</span><br><span class="line">        <span class="title function_">onFocus</span>(<span class="params"></span>)&#123; <span class="regexp">/_ 声明方法用于聚焦 input 框 _/</span></span><br><span class="line">       inputRef.<span class="property">current</span>.<span class="title function_">focus</span>()</span><br><span class="line">     &#125;,</span><br><span class="line">      <span class="title function_">onChangeValue</span>(<span class="params">value</span>)&#123; <span class="regexp">/_ 声明方法用于改变 input 的值 _/</span></span><br><span class="line">       <span class="title function_">setInputValue</span>(value)</span><br><span class="line">     &#125;</span><br><span class="line">    &#125;</span><br><span class="line">      <span class="keyword">return</span> handleRefs</span><br><span class="line">  &#125;,[])</span><br><span class="line">  <span class="keyword">return</span></span><br><span class="line">  <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">placeholder</span>=<span class="string">&quot;请输入内容&quot;</span>  <span class="attr">ref</span>=<span class="string">&#123;inputRef&#125;</span>  <span class="attr">value</span>=<span class="string">&#123;inputValue&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ForwarSon</span> = <span class="title function_">forwardRef</span>(<span class="title class_">Son</span>)</span><br><span class="line">  <span class="comment">// 父组件</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Index</span> <span class="keyword">extends</span> <span class="title class_ inherited__">React.Component</span>&#123;</span><br><span class="line">  cur = <span class="literal">null</span></span><br><span class="line">  <span class="title function_">handerClick</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="keyword">const</span> &#123; onFocus , onChangeValue &#125; =<span class="variable language_">this</span>.<span class="property">cur</span></span><br><span class="line">    <span class="title function_">onFocus</span>() <span class="comment">// 让子组件的输入框获取焦点</span></span><br><span class="line">    <span class="title function_">onChangeValue</span>(<span class="string">&#x27;let us learn React!&#x27;</span>) <span class="comment">// 让子组件 input</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title function_">render</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> </span><br><span class="line">       <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&#123;&#123;</span> <span class="attr">marginTop:</span>&#x27;<span class="attr">50px</span>&#x27; &#125;&#125; &gt;</span></span></span><br><span class="line"><span class="language-xml">          <span class="tag">&lt;<span class="name">ForwarSon</span> <span class="attr">ref</span>=<span class="string">&#123;cur</span> =&gt;</span> (this.cur = cur)&#125; /&gt;</span></span><br><span class="line"><span class="language-xml">          <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;this.handerClick.bind(this)&#125;</span> &gt;</span>操控子组件<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">      &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</code></pre>
<h2 id="ref组件缓存数据"><a href="#ref组件缓存数据" class="headerlink" title="ref组件缓存数据"></a>ref组件缓存数据</h2><p>   &emsp;在执行一些事件或者方法改变数据或者保留数据,有没有必要更新视图,有没有必要把数据放在state中。如果更新视图不依赖需要改变的数据,那么state带来的更新效果无疑闲的的多余。这时候就可以使用ref,好处有2个</p>
<ul>
<li>第一个能够直接修改数据,不会造成函数组件冗余的更新作用</li>
<li>第二个useRef保存数据,无需将ref对象添加dep依赖项,因为uesRef始终指向一个内存空间,所以这样的好处是<font color="red" >随时可以获取到最新的值</font></li>
</ul>
<pre><code>
</code></pre>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://leachliu.gitee.io">刘超</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://leachliu.gitee.io/2022/01/05/react/%E5%A4%9A%E5%8A%9F%E8%83%BDRef/">https://leachliu.gitee.io/2022/01/05/react/%E5%A4%9A%E5%8A%9F%E8%83%BDRef/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://leachliu.gitee.io" target="_blank">刘超的博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Ref/">Ref</a></div><div class="post_share"><div class="social-share" data-image="/images/avatar.webp" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/01/20/react/layout%E5%B8%83%E5%B1%80%E6%9E%84%E5%BB%BA/" title="layout布局构建(React项目搭建6)"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">layout布局构建(React项目搭建6)</div></div></a></div><div class="next-post pull-right"><a href="/2021/12/30/react/class%E4%B8%AD%E7%9A%84state%E5%92%8Chooks%E4%B8%AD%E7%9A%84state/" title="class中的state和hooks中的state"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">class中的state和hooks中的state</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/images/avatar.webp" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">刘超</div><div class="author-info__description">只有自己强大，才不会被别人践踏。</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">41</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">6</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=923946406&amp;site=qq&amp;menu=yes" target="_blank" title="QQ"><i class="fab fa-qq"></i></a><a class="social-icon" href="https://chao-picture-bed.oss-cn-hangzhou.aliyuncs.com/blog/vue/popperJs/202301131417748.jpg" target="_blank" title="Wechat"><i class="fab fa-weixin"></i></a><a class="social-icon" href="/923946406@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://github.com/tzy13755126023" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="Rss"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">书山有路勤为径,学海无涯苦作舟</div></div><div class="card-widget tzy-right-widget" id="card-wechat"><div id="flip-wrapper"><div id="flip-content"><div class="face"></div><div class="back face"></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Ref-%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5%E5%92%8C%E4%BD%BF%E7%94%A8"><span class="toc-number">1.</span> <span class="toc-text">Ref 基本概念和使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB%E7%BB%84%E4%BB%B6%E8%8E%B7%E5%8F%96-Ref-%E7%9A%84%E6%96%B9%E5%BC%8F"><span class="toc-number">2.</span> <span class="toc-text">类组件获取 Ref 的方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Ref-%E9%AB%98%E9%98%B6%E7%94%A8%E6%B3%95"><span class="toc-number">3.</span> <span class="toc-text">Ref 高阶用法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%AB%98%E9%98%B6%E7%BB%84%E4%BB%B6%E8%BD%AC%E5%8F%91"><span class="toc-number">4.</span> <span class="toc-text">高阶组件转发</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#ref%E7%BB%84%E4%BB%B6%E7%BC%93%E5%AD%98%E6%95%B0%E6%8D%AE"><span class="toc-number">5.</span> <span class="toc-text">ref组件缓存数据</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/11/06/comlibary/4.%E7%BB%84%E4%BB%B6%E5%BA%93%E7%B1%BB%E5%90%8D%E6%96%B9%E6%B3%95%E5%AE%9E%E7%8E%B0%E4%BB%A5%E5%8F%8A%E8%A7%84/" title="无题">无题</a><time datetime="2023-11-06T07:16:00.298Z" title="发表于 2023-11-06 15:16:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/06/comlibary/3.%E6%90%AD%E5%BB%BA%E7%BB%84%E4%BB%B6%E5%BA%93%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/" title="组件库框架 - 3 搭建组件库开发环境"><img src="/images/beijing4.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 3 搭建组件库开发环境"/></a><div class="content"><a class="title" href="/2023/11/06/comlibary/3.%E6%90%AD%E5%BB%BA%E7%BB%84%E4%BB%B6%E5%BA%93%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83/" title="组件库框架 - 3 搭建组件库开发环境">组件库框架 - 3 搭建组件库开发环境</a><time datetime="2023-11-06T06:30:00.000Z" title="发表于 2023-11-06 14:30:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/11/06/comlibary/2.%E5%88%9D%E5%A7%8B%E5%8C%96workspace-root/" title="组件库框架 - 2 初始化workspace-root"><img src="/images/beijing4.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 2 初始化workspace-root"/></a><div class="content"><a class="title" href="/2023/11/06/comlibary/2.%E5%88%9D%E5%A7%8B%E5%8C%96workspace-root/" title="组件库框架 - 2 初始化workspace-root">组件库框架 - 2 初始化workspace-root</a><time datetime="2023-11-06T03:18:00.000Z" title="发表于 2023-11-06 11:18:00">2023-11-06</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/10/27/comlibary/1.%E6%90%AD%E5%BB%BApnpm%E3%80%81monorepo/" title="组件库框架 - 1 搭建pnpn monorepo"><img src="/images/beijing3.webp" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="组件库框架 - 1 搭建pnpn monorepo"/></a><div class="content"><a class="title" href="/2023/10/27/comlibary/1.%E6%90%AD%E5%BB%BApnpm%E3%80%81monorepo/" title="组件库框架 - 1 搭建pnpn monorepo">组件库框架 - 1 搭建pnpn monorepo</a><time datetime="2023-10-27T06:36:00.000Z" title="发表于 2023-10-27 14:36:00">2023-10-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/01/12/other/%E4%BD%BF%E7%94%A8OSS+PicGo%E6%90%AD%E5%BB%BA%E5%9B%BE%E5%BA%8A/" title="使用OSS+PicGo搭建图床"><img src="https://chao-picture-bed.oss-cn-hangzhou.aliyuncs.com/blog/vue/popperJs/202301121557184.png" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="使用OSS+PicGo搭建图床"/></a><div class="content"><a class="title" href="/2023/01/12/other/%E4%BD%BF%E7%94%A8OSS+PicGo%E6%90%AD%E5%BB%BA%E5%9B%BE%E5%BA%8A/" title="使用OSS+PicGo搭建图床">使用OSS+PicGo搭建图床</a><time datetime="2023-01-12T07:39:00.000Z" title="发表于 2023-01-12 15:39:00">2023-01-12</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023  <i id="heartbeat" class="fa fas fa-heartbeat"></i> 刘超</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer src="https://fastly.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/js/search/algolia.js"></script></div></div><!-- hexo injector body_end start --><script async src="//at.alicdn.com/t/font_2032782_8d5kxvn09md.js"></script><!-- hexo injector body_end end --></body></html>